<script lang="ts" setup>
import { loanAudit } from '@/api/lending'
import { loanOrderList } from '@/api/user'

defineOptions({
  name: 'OperationContent',
})

// 数据接口类型定义
interface LoanItem {
  id: number
  user_name: string
  user_telephone: string
  principal: number
  product_name: string
  installment_periods: number
  annual_interest_rate: number
  loan_audit: number
  finance_audit: number
  payment_time: string | null
  repayment_method: string
  order_id: string
  created_time: string
  start_date: string
  end_date: string
  repayment_date: string
  interest: number
  left_interest: number
  left_principal: number
  total_repayment_amount: number
  loan_remark: string
  finance_remark: string
  payment_voucher: string
  steps: any[]
}

// 响应式数据
const loanList = ref<LoanItem[]>([])
const loading = ref(false)

// 暴露activated方法给父组件调用
function actived() {
  console.log('运营页面加载-----------------------------')
  getOrderList()
}

// 暴露方法给父组件
defineExpose({
  actived,
})

// 获取借款工单列表
async function getOrderList() {
  try {
    loading.value = true
    const res = await loanOrderList({
      page: 1,
      size: 9999,
      repayment_tp: 0,
      keyword: searchKeyword.value.trim(), // 使用搜索关键词
      audit_tp: activeTab.value, // 添加审核状态参数
    })
    loanList.value = res.list || []
    console.log('借款工单数据获取成功:', loanList.value)
  }
  catch (error) {
    console.error('获取借款工单数据失败:', error)
    uni.showToast({
      title: '获取数据失败',
      icon: 'none',
    })
  }
  finally {
    loading.value = false
  }
}

// 计算当前步骤
function getCurrentStep(item) {
  // 根据审核状态确定当前步骤
  if (item.payment_time) {
    return 3 // 财务已放款
  }
  else if (item.finance_audit === 1) {
    return 2 // 待财务放款
  }
  else if (item.finance_audit === -2) {
    return -2 // 财务审核拒绝
  }
  else if (item.loan_audit === 1) {
    return 1 // 待财务审核
  }
  else if (item.loan_audit === -2) {
    return -1 // 运营长审核拒绝
  }
  else {
    return 0 // 待运营长审核
  }
}

// 获取还款方式文本
const getRepaymentMethodText = {
  1: '分期还款',
  2: '利润分成',
}

// 组件挂载时获取数据
onMounted(() => {
  getOrderList()
})

// 标签页数据
const tabs = ref([
  { id: -1, name: '全部' },
  { id: 0, name: '待审核' },
  { id: 1, name: '待放款' },
  { id: 2, name: '已完结' },
])

// 当前选中的标签
const activeTab = ref(-1)

// 搜索关键词
const searchKeyword = ref('')

// 步骤列表配置
const stepList = ref([
  { title: '运营长审核' },
  { title: '财务审核' },
  { title: '财务放款' },
  // { title: '已完结' }
])
// 切换标签
function switchTab(tabId: number) {
  activeTab.value = tabId
  getOrderList() // 切换tab时重新获取数据
}

// 监听搜索关键词变化
watch(searchKeyword, () => {
  // 防抖处理，避免频繁请求
  clearTimeout(searchTimer.value)
  searchTimer.value = setTimeout(() => {
    getOrderList()
  }, 1500)
})

// 搜索防抖定时器
const searchTimer = ref<NodeJS.Timeout | null>(null)

// 格式化金额
function formatAmount(amount: number) {
  return amount.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  })
}

// 审核相关数据
const showAuditModal = ref(false)
const currentAuditItem = ref<LoanItem | null>(null)
const auditForm = ref({
  status: 1, // 1通过 2拒绝
  remark: '',
})

// 处理申请操作
function handleAction(item: any, action: string) {
  console.log(`${action} 申请:`, item)
  if (action === 'audit') {
    openAuditModal(item)
  }
}

// 打开审核弹窗
function openAuditModal(item: LoanItem) {
  currentAuditItem.value = item
  auditForm.value = {
    status: 1,
    remark: '',
  }
  showAuditModal.value = true
}

// 关闭审核弹窗
function closeAuditModal() {
  showAuditModal.value = false
  currentAuditItem.value = null
  auditForm.value = {
    status: 1,
    remark: '',
  }
}

// 提交审核
async function submitAudit() {
  if (!currentAuditItem.value)
    return

  if (!auditForm.value.remark.trim()) {
    uni.showToast({
      title: '请输入审核说明',
      icon: 'none',
    })
    return
  }

  try {
    uni.showLoading({
      title: '提交中...',
    })

    await loanAudit(currentAuditItem.value.id, {
      status: auditForm.value.status,
      remark: auditForm.value.remark,
    })

    uni.hideLoading()
    uni.showToast({
      title: '审核提交成功',
      icon: 'success',
    })

    closeAuditModal()
    // 重新获取数据
    getOrderList()
  }
  catch (error) {
    uni.hideLoading()
    console.error('审核提交失败:', error)
    uni.showToast({
      title: '审核提交失败',
      icon: 'none',
    })
  }
}
</script>

<template>
  <view class="operation-page">
    <!-- 标签页 -->
    <view class="tabs-container">
      <view class="tabs">
        <view v-for="tab in tabs" :key="tab.id" class="tab-item" :class="{ active: activeTab === tab.id }"
          @tap="switchTab(tab.id)">
          <text class="tab-text">{{ tab.name }}</text>
          <view v-if="activeTab === tab.id" class="tab-indicator" />
        </view>
      </view>
    </view>

    <!-- 搜索框 -->
    <view class="search-container">
      <view class="search-box">
        <uni-icons type="search" size="18" color="#999" />
        <input v-model="searchKeyword" class="search-input" placeholder="请输入姓名 / 手机号查询"
          placeholder-style="color: #999;">
      </view>
    </view>

    <!-- 申请列表 -->
    <view class="list-container">
      <view v-for="item in loanList" :key="item.id" class="loan-item">
        <!-- 用户信息 -->
        <view class="user-info">
          <view class="user-header">
            <view class="user-name-section">
              <text class="user-name">{{ item.user_name }}</text>
              <text class="user-name">{{ item.user_telephone }}</text>
              <text class="user-name">{{ item.product_name }}</text>
            </view>
          </view>
        </view>

        <!-- 配资信息 -->
        <view class="loan-info flex items-center justify-between">
          <view>
            <view class="loan-row">
              <text class="label">借款：</text>
              <text class="amount">{{ formatAmount(item.principal) }}</text>
            </view>
            <view class="loan-row">
              <text class="label">借款期限：</text>
              <!-- <text class="amount">{{ item.product_name }}</text> -->
              <text class="amount">{{ item.installment_periods }}期</text>
              <text class="amount">{{ getRepaymentMethodText[item.repayment_method] }}</text>
            </view>
            <!-- 运营长审核备注 -->
            <view v-if="item.loan_remark" class="loan-row">
              <text class="label">运营长审核备注：</text>
              <text class="amount">{{ item.loan_remark }}</text>
            </view>
            <!-- 财务审核备注 -->
            <view v-if="item.finance_remark" class="loan-row">
              <text class="label">财务审核备注：</text>
              <text class="amount">{{ item.finance_remark }}</text>
            </view>
          </view>
          <!-- 只有当loan_audit为0时才显示审核按钮 -->
          <view v-if="item.loan_audit === 0" class="action-button" @tap="handleAction(item, 'audit')">
            <text class="btn-text">去审核</text>
          </view>
        </view>

        <!-- 步骤条 -->
        <view class="step-wrapper">
          <view class="custom-steps">
            <view class="step-container">
              <view v-for="(step, index) in stepList" :key="index" class="step-item" :class="{
                completed: index < getCurrentStep(item) && getCurrentStep(item) > 0,
                rejected: (getCurrentStep(item) === -1 && index === 0) || (getCurrentStep(item) === -2 && index === 1),
              }">
                <view class="step-dot" />
                <text class="step-title">{{ step.title }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-if="loanList.length === 0" class="empty-state">
        <text class="empty-text">暂无数据</text>
      </view>
    </view>

    <!-- 审核弹窗 -->
    <view v-if="showAuditModal" class="audit-modal" @tap="closeAuditModal">
      <view class="audit-content" @tap.stop>
        <view class="audit-header">
          <text class="audit-title">审核申请</text>
          <view class="close-btn" @tap="closeAuditModal">
            <uni-icons type="close" size="20" color="#999" />
          </view>
        </view>

        <view class="audit-info">
          <view class="info-row">
            <text class="info-label">申请人：</text>
            <text class="info-value">{{ currentAuditItem?.user_name }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">借款金额：</text>
            <text class="info-value">{{ formatAmount(currentAuditItem?.principal || 0) }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">借款期限：</text>
            <text class="info-value">{{ currentAuditItem?.installment_periods }}期</text>
          </view>
        </view>

        <view class="audit-form">
          <view class="form-item">
            <text class="form-label">审核结果</text>
            <view class="radio-group">
              <view class="radio-item" :class="{ active: auditForm.status === 1 }" @tap="auditForm.status = 1">
                <view class="radio-dot" />
                <text class="radio-text">通过</text>
              </view>
              <view class="radio-item" :class="{ active: auditForm.status === -2 }" @tap="auditForm.status = -2">
                <view class="radio-dot" />
                <text class="radio-text">拒绝</text>
              </view>
            </view>
          </view>

          <view class="form-item">
            <text class="form-label">审核说明</text>
            <textarea v-model="auditForm.remark" class="audit-textarea" placeholder="请输入审核说明"
              placeholder-style="color: #999;" :maxlength="200" />
          </view>
        </view>

        <view class="audit-actions">
          <view class="action-btn cancel" @tap="closeAuditModal">
            <text class="btn-text">取消</text>
          </view>
          <view class="action-btn confirm" @tap="submitAudit">
            <text class="btn-text">提交</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
// 标签页样式
.tabs-container {
  background-color: #fff;
  padding: 0 32rpx;
}

.tabs {
  display: flex;
  height: 88rpx;
}

.tab-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
  height: 100%;
}

.tab-text {
  font-size: 32rpx;
  color: #666;
  font-weight: 500;
}

.tab-item.active .tab-text {
  color: #fb953b;
  font-weight: 600;
}

.tab-indicator {
  position: absolute;
  bottom: 0;
  width: 60rpx;
  height: 6rpx;
  background-color: #fb953b;
  border-radius: 3rpx;
}

// 搜索框样式
.search-container {
  padding: 24rpx 32rpx;
  background-color: #fff;
  border-bottom: 2rpx solid #f0f0f0;
}

.search-box {
  display: flex;
  align-items: center;
  background-color: #f8f8f8;
  border-radius: 48rpx;
  padding: 20rpx 32rpx;
  gap: 16rpx;
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

// 列表样式
.list-container {
  padding: 24rpx 32rpx;
}

.loan-item {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

// 用户信息样式
.user-info {
  margin-bottom: 24rpx;
}

.user-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.user-name-section {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 16rpx;
  flex-wrap: wrap;
}

.user-name {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.phone {
  font-size: 28rpx;
  color: #666;
}

.city-role {
  font-size: 28rpx;
  color: #666;
}

.action-button {
  background-color: #fb953b;
  border-radius: 32rpx;
  padding: 12rpx 24rpx;
  min-width: 120rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-text {
  font-size: 24rpx;
  color: #fff;
  font-weight: 500;
}

// 配资信息样式
.loan-info {
  margin-bottom: 24rpx;
}

.loan-row {
  display: flex;
  align-items: center;
  margin-bottom: 12rpx;
  gap: 16rpx;
  flex-wrap: wrap;
}

.label {
  font-size: 28rpx;
  color: #666;
  min-width: 80rpx;
}

.amount {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
}

.period-text {
  font-size: 28rpx;
  color: #666;
}

.status-text {
  font-size: 28rpx;
  color: #666;
}

.custom-steps {
  width: 100%;
}

.step-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: relative;

  &::before {
    content: '';
    position: absolute;
    top: 16rpx;
    left: 32rpx;
    right: 32rpx;
    height: 2rpx;
    background: none;
    border-top: 2rpx dashed #e0e0e0;
    z-index: 1;
  }
}

.step-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  z-index: 2;
  flex: 1;
}

.step-dot {
  width: 32rpx;
  height: 32rpx;
  border-radius: 50%;
  background-color: #e0e0e0;
  margin-bottom: 12rpx;
  transition: all 0.3s ease;
}

.step-item.completed .step-dot {
  background-color: #fb953b;
}

.step-item.rejected .step-dot {
  background-color: #ff4757;
}

.step-item.rejected .step-title {
  color: #ff4757;
}

.step-title {
  font-size: 24rpx;
  color: #999;
  text-align: center;
  line-height: 1.2;
  max-width: 120rpx;
}

// 操作按钮样式
.action-buttons {
  display: flex;
  align-items: center;
  gap: 16rpx;
  justify-content: flex-end;
}

.action-btn {
  width: 64rpx;
  height: 64rpx;
  border-radius: 50%;
  background-color: #f8f8f8;
  display: flex;
  align-items: center;
  justify-content: center;

  &.primary {
    background-color: #fb953b;
    width: auto;
    padding: 0 24rpx;
    border-radius: 32rpx;
  }
}

.btn-text {
  font-size: 24rpx;
  color: #fff;
  font-weight: 500;
}

// 空状态样式
.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

// 审核弹窗样式
.audit-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.audit-content {
  background-color: #fff;
  border-radius: 16rpx;
  width: 640rpx;
  max-height: 80vh;
  overflow-y: auto;
}

.audit-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.audit-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.close-btn {
  width: 48rpx;
  height: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.audit-info {
  padding: 32rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.info-label {
  font-size: 28rpx;
  color: #666;
  width: 160rpx;
}

.info-value {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.audit-form {
  padding: 32rpx;
}

.form-item {
  margin-bottom: 32rpx;
}

.form-label {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 16rpx;
  display: block;
}

.radio-group {
  display: flex;
  gap: 32rpx;
}

.radio-item {
  display: flex;
  align-items: center;
  gap: 12rpx;
  cursor: pointer;
}

.radio-dot {
  width: 32rpx;
  height: 32rpx;
  border: 4rpx solid #ddd;
  border-radius: 50%;
  position: relative;
  transition: all 0.3s ease;
}

.radio-item.active .radio-dot {
  border-color: #fb953b;
}

.radio-item.active .radio-dot::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 16rpx;
  height: 16rpx;
  background-color: #fb953b;
  border-radius: 50%;
}

.radio-text {
  font-size: 28rpx;
  color: #333;
}

.audit-textarea {
  width: 100%;
  min-height: 160rpx;
  padding: 16rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #333;
  resize: none;
  box-sizing: border-box;
}

.audit-actions {
  display: flex;
  gap: 24rpx;
  padding: 32rpx;
  border-top: 2rpx solid #f0f0f0;
}

.action-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  font-weight: 500;
}

.action-btn.cancel {
  background-color: #f5f5f5;
  color: #666;
}

.action-btn.confirm {
  background-color: #fb953b;
  color: #fff;
}
</style>
